const path = require("path");
const http = require("http");
const express = require("express");
const socketio = require("socket.io");
const moment = require("moment");
const { userJoin, userLeave, getRoomUsers } = require("./utils/user");

const app = express();
const server = http.createServer(app);
const io = socketio(server);

app.use(express.static(path.join(__dirname, "public")));

function emitRoomUsers(room) {
    io.to(room).emit("roomUsers", getRoomUsers(room));
}

io.on("connection", (socket) => {
    //socket.emit("sysMessage", "欢迎加入聊天室");

    //socket.emit("sysMessage", "一个新用户加入了聊天室");
    
    socket.on("joinRoom", ({ name, room }) => {
        socket.join(room);

        userJoin(socket.id, name, room);

        emitRoomUsers(room);

        socket.on("chatMessage", (message) => {
            io.to(room).emit("chatMessage", {
                ...message,
                time: moment().utcOffset(8).format("HH:mm:ss"),
            });
        });

        socket.on("disconnect", () => {
            //io.emit("sysMessage", "一个用户离开了聊天室");

            userLeave(socket.id);

            emitRoomUsers(room);
        });
    });
});

const PORT = process.env.PORT || 9527 ;

server.listen(PORT, () => console.log(`Server runing on port ${PORT}`));


